package com.pyue.eam.admin.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.pyue.eam.common.data.tenant.TenantContextHolder;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Date 2021-02-24 13:57
 * 要求该工具存 需要该工具取
 */
@Component
@AllArgsConstructor
public class RedisTemplateUtil {
    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 删除多个租户对应对应的value
     */
    public void removeByTenantIdList(List<Long> tenantIdList, final String key) {
        if (CollUtil.isNotEmpty(tenantIdList)) {
            tenantIdList.forEach(e -> removeByTenantId(e, key));
        }
    }

    /**
     * 正则匹配方式删除数据
     */
    public void removeByTenantIdListPattern(List<Integer> tenantIdList, final String key) {
        if (CollUtil.isNotEmpty(tenantIdList)) {
            tenantIdList.parallelStream().forEach(e -> removeByTenantIdPattern(e, key));
        }
    }

    /**
     * 正则匹配方式删除数据
     *
     * @param tenantId
     * @param key
     */
    public void removeByTenantIdPattern(Integer tenantId, final String key) {
        Set<String> keys = redisTemplate.keys(Convert.toStr(tenantId) + StrUtil.COLON + key + "*");
        if (CollUtil.isNotEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除单个租户对应对应的value
     *
     * @param key
     */
    public void removeByTenantId(Long tenantId, final String key) {
        String tenantKey = Convert.toStr(tenantId) + StrUtil.COLON + key;
        if (exists(tenantKey)) {
            redisTemplate.delete(tenantKey);
        }
    }

    public void removeByDefaultTenantId(String key) {
        removeByTenantId(TenantContextHolder.getTenantId(), key);
    }


    /**
     * 判断缓存中是否有对应的value
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     */
    public <T> T getToClass(final String key, Class<T> clazz) {
        Object o = redisTemplate.opsForValue().get(key);
        if (o != null) {
            return BeanUtil.toBean(o, clazz);
        }
        return null;
    }

    /**
     * 写入缓存
     */
    public <T> boolean set(final String key, T value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 设置超时时间
     */
    public <T> boolean set(final String key, T value, Long expireTime) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存,带过期时间
     *
     * @param key
     * @param value
     * @param expireHour SECONDS
     */
    public <T> boolean setByHour(final String key, T value, Long expireHour) {
        return set(key, value, expireHour * 60 * 60);
    }

    /**
     * List集合写入缓存
     */
    public boolean setList(final String key, Object object) {
        boolean result = false;
        try {
            redisTemplate.opsForList().rightPush(key, object);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * List集合写入缓存,带过期时间
     */
    public boolean setList(final String key, Object object, Long expireTime) {
        boolean result = false;
        try {
            redisTemplate.opsForList().rightPush(key, object);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * List集合整个写入缓存
     */
    public boolean setListAll(final String key, List list) {
        boolean result = false;
        try {
            redisTemplate.opsForList().rightPushAll(key, list);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * List集合整个写入缓存,带过期时间
     */
    public boolean setListAll(final String key, List list, Long expireTime) {
        boolean result = false;
        try {
            redisTemplate.opsForList().rightPushAll(key, list);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取List集合
     */
    public List getAllList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 获取List集合
     */
    public List getList(final String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * 获取Set集合
     */
    public Set getSet(final String key) {
        Set result = null;
        result = redisTemplate.opsForSet().members(key);
        return result;
    }

    /**
     * Set集合写入缓存,带过期时间
     */
    public boolean setSet(final String key, Object object, Long expireTime) {
        boolean result = false;
        try {
            SetOperations<String, Object> setOperations = redisTemplate.opsForSet();
            setOperations.add(key, object);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean setSet(final String key, Set set, Long expireTime) {
        boolean result = false;
        try {
            SetOperations<String, Object> setOperations = redisTemplate.opsForSet();
            for (Object o : set) {
                setOperations.add(key, o);
            }
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Set集合写入缓存
     */
    public boolean setSet(final String key, Set set) {
        boolean result = false;
        try {
            SetOperations<String, Object> setOperations = redisTemplate.opsForSet();
            for (Object o : set) {
                setOperations.add(key, o);
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean setSet(final String key, Object object) {
        boolean result = false;
        try {
            SetOperations<String, Object> setOperations = redisTemplate.opsForSet();
            setOperations.add(key, object);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Map集合写入缓存
     */
    public boolean setMap(final String key, Map map) {
        return setMap(key, map, null);
    }

    /**
     * Map集合写入缓存,带过期时间
     */
    public boolean setMap(final String key, Map map, Long expireTime) {
        boolean result = false;
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (expireTime != null) {
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 取出Map集合
     */
    public Map getMap(final String key) {
        Map result = null;
        result = redisTemplate.opsForHash().entries(key);
        return result;
    }

    /**
     * 获取自增ID
     */
    public Long incr(String key) {
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = redisAtomicLong.getAndIncrement();
        return increment;
    }

    /**
     * 获取自增ID 并设置过期时间
     */
    public Long incr(String key, Long expireTime) {
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        redisAtomicLong.expire(expireTime, TimeUnit.SECONDS);
        Long increment = redisAtomicLong.getAndIncrement();
        return increment;
    }

}
